package com.yueyang.sojourn.server.common.baymax.web.resolver;

import com.yueyang.sojourn.server.common.baymax.web.result.RestResult;

/**
 * 从异常中获取可能的业务码信息，如果异常无法解析出业务码，则默认返回的业务码为未知。
 * 
 * @author Huisman (SE)
 * @Copyright (c) 2017, yueyang Group All Rights Reserved.
 */
public final class BizCodes {
  /**
   * Http Response X-Error-Code
   * </p>
   * 我们将业务码放到Header里返回。
   */
  public static String HEADERS_X_ERROR_CODE = "X-Error-Code";

  private BizCodes() {
    throw new UnsupportedOperationException();
  }

  /**
   * 从异常中获取可能的业务码信息，如果异常无法解析出业务码，则默认返回的业务码为未知。
   * 
   * @author huisman
   * @param ex 异常信息
   * @return never return null
   */
  public static RPCRestResult from(Exception ex) {
    if (ex == null) {
      return new RPCRestResult("");
    }
    RestResponseMessage rrm = RestResponseMessageProviders.getRestResponseMessage(ex);
    if (rrm == null) {
      return new RPCRestResult(ex.getMessage());
    }
    return new RPCRestResult(rrm.getCode(), rrm.getMessage(), rrm.isRequestSucceeded());
  }

  /**
   * 远程调用解析出来的业务码
   */
  public static final class RPCRestResult implements RestResult {
    private final int code;
    private final String message;
    private final boolean requestSucceeded;

    RPCRestResult(String message) {
      this.code = Codes.UNKNOWN;
      this.message = message;
      this.requestSucceeded = false;
    }

    RPCRestResult(int code, String message, boolean requestSucceeded) {
      super();
      this.code = code;
      this.message = message;
      this.requestSucceeded = requestSucceeded;
    }

    @Override
    public int getCode() {
      return this.code;
    }

    @Override
    public String getMessage() {
      return this.message;
    }

    /**
     * 请求是否发送成功并收到响应。
     * RPC调用时，如果代码执行异常则返回false，比如，网络链接超时、读取超时、方法执行超时
     */
    public boolean isRequestSucceeded() {
      return this.requestSucceeded;
    }

    /*
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
      return "RPCRestResult [code=" + code + ", message=" + message + ", requestSucceeded="
          + requestSucceeded + "]";
    }

  }
}
